home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2008 February / PCWFEB08.iso / Software / Freeware / Miro 1.0 / Miro_Installer.exe / xulrunner / python / site.py < prev    next >
Encoding:
Python Source  |  2007-11-12  |  10.5 KB  |  322 lines

  1. # Miro - an RSS based video player application
  2. # Copyright (C) 2005-2007 Participatory Culture Foundation
  3. #
  4. # This program is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License as published by
  6. # the Free Software Foundation; either version 2 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
  17.  
  18. #import sys
  19. #class AutoflushingStream:
  20. #    def __init__(self, stream):
  21. #        self.stream = stream
  22. #    def write(self, *args):
  23. #        self.stream.write(*args)
  24. #        self.stream.flush()
  25. #mylog = open("\\sitelog","wt")
  26. #sys.stdout = sys.stderr = AutoflushingStream(mylog)
  27. #print "this is sitelog; path now %s" % sys.path
  28.  
  29. """Customized site-setup script that leaves sys.path alone.
  30.  
  31. In a normal Python implementation, this module is automatically
  32. imported at startup, and sets up sys.path using various heuristics,
  33. and then does incidental other platform-dependent, heuristic-based
  34. initialization.
  35.  
  36. We want sys.path to be exactly one entry, so I've stripped out
  37. everything that has to do with augumenting sys.path and for the most
  38. part left the other incidental initializations alone. One exception to
  39. the first part of that sentence is that the logic for dealing with
  40. .pth files has been left alone, just in case.
  41.  
  42. In any event, this is the very first Python code that runs.
  43. """
  44.  
  45. import sys
  46. import os
  47. import __builtin__
  48.  
  49. # Make up for the fact that it was probably (hopefully??!) impossible
  50. # to import the warnings module during Py_Initialize. Python is
  51. # designed to deal with this case and gracefully notice that it was
  52. # provided later.
  53. import warnings 
  54.  
  55. def makepath(*paths):
  56.     dir = os.path.abspath(os.path.join(*paths))
  57.     return dir, os.path.normcase(dir)
  58.  
  59. def abs__file__():
  60.     """Set all module' __file__ attribute to an absolute path"""
  61.     for m in sys.modules.values():
  62.         try:
  63.             m.__file__ = os.path.abspath(m.__file__)
  64.         except AttributeError:
  65.             continue
  66.  
  67. def removeduppaths():
  68.     """ Remove duplicate entries from sys.path along with making them
  69.     absolute"""
  70.     # This ensures that the initial path provided by the interpreter contains
  71.     # only absolute pathnames, even if we're running from the build directory.
  72.     L = []
  73.     known_paths = set()
  74.     for dir in sys.path:
  75.         # Filter out duplicate paths (on case-insensitive file systems also
  76.         # if they only differ in case); turn relative paths into absolute
  77.         # paths.
  78.         dir, dircase = makepath(dir)
  79.         if not dircase in known_paths:
  80.             L.append(dir)
  81.             known_paths.add(dircase)
  82.     sys.path[:] = L
  83.     return known_paths
  84.  
  85. def _init_pathinfo():
  86.     """Return a set containing all existing directory entries from sys.path"""
  87.     d = set()
  88.     for dir in sys.path:
  89.         try:
  90.             if os.path.isdir(dir):
  91.                 dir, dircase = makepath(dir)
  92.                 d.add(dircase)
  93.         except TypeError:
  94.             continue
  95.     return d
  96.  
  97. def addpackage(sitedir, name, known_paths):
  98.     """Add a new path to known_paths by combining sitedir and 'name' or execute
  99.     sitedir if it starts with 'import'"""
  100.     if known_paths is None:
  101.         _init_pathinfo()
  102.         reset = 1
  103.     else:
  104.         reset = 0
  105.     fullname = os.path.join(sitedir, name)
  106.     try:
  107.         f = open(fullname, "rU")
  108.     except IOError:
  109.         return
  110.     try:
  111.         for line in f:
  112.             if line.startswith("#"):
  113.                 continue
  114.             if line.startswith("import"):
  115.                 exec line
  116.                 continue
  117.             line = line.rstrip()
  118.             dir, dircase = makepath(sitedir, line)
  119.             if not dircase in known_paths and os.path.exists(dir):
  120.                 sys.path.append(dir)
  121.                 known_paths.add(dircase)
  122.     finally:
  123.         f.close()
  124.     if reset:
  125.         known_paths = None
  126.     return known_paths
  127.  
  128. def addsitedir(sitedir, known_paths=None):
  129.     """Add 'sitedir' argument to sys.path if missing and handle .pth files in
  130.     'sitedir'"""
  131.     if known_paths is None:
  132.         known_paths = _init_pathinfo()
  133.         reset = 1
  134.     else:
  135.         reset = 0
  136.     sitedir, sitedircase = makepath(sitedir)
  137.     if not sitedircase in known_paths:
  138.         sys.path.append(sitedir)        # Add path component
  139.     try:
  140.         names = os.listdir(sitedir)
  141.     except os.error:
  142.         return
  143.     names.sort()
  144.     for name in names:
  145.         if name.endswith(os.extsep + "pth"):
  146.             addpackage(sitedir, name, known_paths)
  147.     if reset:
  148.         known_paths = None
  149.     return known_paths
  150.  
  151.  
  152. def setquit():
  153.     """Define new built-ins 'quit' and 'exit'.
  154.     These are simply strings that display a hint on how to exit.
  155.  
  156.     """
  157.     if os.sep == ':':
  158.         exit = 'Use Cmd-Q to quit.'
  159.     elif os.sep == '\\':
  160.         exit = 'Use Ctrl-Z plus Return to exit.'
  161.     else:
  162.         exit = 'Use Ctrl-D (i.e. EOF) to exit.'
  163.     __builtin__.quit = __builtin__.exit = exit
  164.  
  165.  
  166. class _Printer(object):
  167.     """interactive prompt objects for printing the license text, a list of
  168.     contributors and the copyright notice."""
  169.  
  170.     MAXLINES = 23
  171.  
  172.     def __init__(self, name, data, files=(), dirs=()):
  173.         self.__name = name
  174.         self.__data = data
  175.         self.__files = files
  176.         self.__dirs = dirs
  177.         self.__lines = None
  178.  
  179.     def __setup(self):
  180.         if self.__lines:
  181.             return
  182.         data = None
  183.         for dir in self.__dirs:
  184.             for filename in self.__files:
  185.                 filename = os.path.join(dir, filename)
  186.                 try:
  187.                     fp = file(filename, "rU")
  188.                     data = fp.read()
  189.                     fp.close()
  190.                     break
  191.                 except IOError:
  192.                     pass
  193.             if data:
  194.                 break
  195.         if not data:
  196.             data = self.__data
  197.         self.__lines = data.split('\n')
  198.         self.__linecnt = len(self.__lines)
  199.  
  200.     def __repr__(self):
  201.         self.__setup()
  202.         if len(self.__lines) <= self.MAXLINES:
  203.             return "\n".join(self.__lines)
  204.         else:
  205.             return "Type %s() to see the full %s text" % ((self.__name,)*2)
  206.  
  207.     def __call__(self):
  208.         self.__setup()
  209.         prompt = 'Hit Return for more, or q (and Return) to quit: '
  210.         lineno = 0
  211.         while 1:
  212.             try:
  213.                 for i in range(lineno, lineno + self.MAXLINES):
  214.                     print self.__lines[i]
  215.             except IndexError:
  216.                 break
  217.             else:
  218.                 lineno += self.MAXLINES
  219.                 key = None
  220.                 while key is None:
  221.                     key = raw_input(prompt)
  222.                     if key not in ('', 'q'):
  223.                         key = None
  224.                 if key == 'q':
  225.                     break
  226.  
  227. def setcopyright():
  228.     """Set 'copyright' and 'credits' in __builtin__"""
  229.     __builtin__.copyright = _Printer("copyright", sys.copyright)
  230.     if sys.platform[:4] == 'java':
  231.         __builtin__.credits = _Printer(
  232.             "credits",
  233.             "Jython is maintained by the Jython developers (www.jython.org).")
  234.     else:
  235.         __builtin__.credits = _Printer("credits", """\
  236.     Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
  237.     for supporting Python development.  See www.python.org for more information.""")
  238.     here = os.path.dirname(os.__file__)
  239.     __builtin__.license = _Printer(
  240.         "license", "See http://www.python.org/%.3s/license.html" % sys.version,
  241.         ["LICENSE.txt", "LICENSE"],
  242.         [os.path.join(here, os.pardir), here, os.curdir])
  243.  
  244.  
  245. class _Helper(object):
  246.     """This normally handles the built-in 'help', but here it's stubbed
  247. out to avoid pulling in pydoc."""
  248.     def __repr__(self):
  249.         return "Help not available."
  250.     def __call__(self, *args, **kwds):
  251.         return "Help not available."
  252.  
  253. def sethelper():
  254.     __builtin__.help = _Helper()
  255.  
  256. def aliasmbcs():
  257.     """On Windows, some default encodings are not provided by Python,
  258.     while they are always available as "mbcs" in each locale. Make
  259.     them usable by aliasing to "mbcs" in such a case."""
  260.     if sys.platform == 'win32':
  261.         import locale, codecs
  262.         enc = locale.getdefaultlocale()[1]
  263.         if enc.startswith('cp'):            # "cp***" ?
  264.             try:
  265.                 codecs.lookup(enc)
  266.             except LookupError:
  267.                 import encodings
  268.                 encodings._cache[enc] = encodings._unknown
  269.                 encodings.aliases.aliases[enc] = 'mbcs'
  270.  
  271. def setencoding():
  272.     """Set the string encoding used by the Unicode implementation.  The
  273.     default is 'ascii', but if you're willing to experiment, you can
  274.     change this."""
  275.     encoding = "utf-8" # The character set of the Democracy log file
  276.     if 0:
  277.         # Enable to support locale aware default string encodings.
  278.         import locale
  279.         loc = locale.getdefaultlocale()
  280.         if loc[1]:
  281.             encoding = loc[1]
  282.     if 0:
  283.         # Enable to switch off string to Unicode coercion and implicit
  284.         # Unicode to string conversion.
  285.         encoding = "undefined"
  286.     if encoding != "ascii":
  287.         # On Non-Unicode builds this will raise an AttributeError...
  288.         sys.setdefaultencoding(encoding) # Needs Python Unicode build !
  289.  
  290. def execsitecustomize():
  291.     """Run custom site specific code, if available."""
  292.     try:
  293.         import sitecustomize
  294.     except ImportError:
  295.         pass
  296.  
  297. def main():
  298.     abs__file__()
  299.     paths_in_sys = removeduppaths()
  300.     setquit()
  301.     setcopyright()
  302.     sethelper()
  303.     aliasmbcs()
  304.     setencoding()
  305.     execsitecustomize()
  306.     # Remove sys.setdefaultencoding() so that users cannot change the
  307.     # encoding after initialization.  The test for presence is needed when
  308.     # this module is run as a script, because this code is executed twice.
  309.     if hasattr(sys, "setdefaultencoding"):
  310.         del sys.setdefaultencoding
  311.  
  312. main()
  313.  
  314. def _test():
  315.     print "sys.path = ["
  316.     for dir in sys.path:
  317.         print "    %r," % (dir,)
  318.     print "]"
  319.  
  320. if __name__ == '__main__':
  321.     _test()
  322.